using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;

namespace AloneLibrary.Services.Input
{
	/// <summary>
	/// This is a game component that implements IUpdateable.
	/// </summary>
	public class KeyboardInputHandler : Microsoft.Xna.Framework.GameComponent, IInputHandler
	{
		#region IInputHandler
		private Vector2 movement = Vector2.Zero;
		private Vector2 rotation = Vector2.Zero;
		private bool start = false;
		private bool back = false;
		private bool fire = false;
		private bool jump = false;
		private bool boost = false;

		public Vector2 Movement
		{
			get { return movement; }
		}
		public Vector2 Rotation
		{
			get { return rotation; }
		}
		public bool Start
		{
			get { return start; }
		}
		public bool Back
		{
			get { return back; }
		}		
		public bool Fire
		{
			get { return fire; }
		}
		public bool Jump
		{
			get { return jump; }
		}
		public bool Boost
		{
			get { return boost; }
		}
		#endregion

		private float mouseSensitivity = 0.5f;
		public float MouseSensitivity
		{
			get { return mouseSensitivity; }
			set { mouseSensitivity = value; }
		}

		private MouseState mouseState;
		private MouseState referenceMouseState;
		private KeyboardState keyboardState;

		public KeyboardInputHandler(Game game)
			: base(game)
		{
			game.Services.AddService(typeof(IInputHandler), this);
			referenceMouseState = Mouse.GetState();
		}

		/// <summary>
		/// Allows the game component to perform any initialization it needs to before starting
		/// to run.  This is where it can query for any required services and load content.
		/// </summary>
		public override void Initialize()
		{
			base.Initialize();
		}

		/// <summary>
		/// Allows the game component to update itself.
		/// </summary>
		/// <param name="gameTime">Provides a snapshot of timing values.</param>
		public override void Update(GameTime gameTime)
		{
			keyboardState = Keyboard.GetState();

			start = keyboardState.IsKeyDown(Keys.Enter);
			back = keyboardState.IsKeyDown(Keys.Escape);
			jump = keyboardState.IsKeyDown(Keys.Space);
			boost = keyboardState.IsKeyDown(Keys.Q);

			fire = (mouseState.LeftButton == ButtonState.Pressed);

			movement.X = (keyboardState.IsKeyDown(Keys.A) ? -1 : (keyboardState.IsKeyDown(Keys.D) ? 1 : 0));
			movement.Y = (keyboardState.IsKeyDown(Keys.S) ? -1 : (keyboardState.IsKeyDown(Keys.W) ? 1 : 0));

			referenceMouseState = mouseState;
			mouseState = Mouse.GetState();

			base.Update(gameTime);
		}

	}
}